package com.zyh.controller;

import com.zyh.config.RandomValidateCodeUtil;
import com.zyh.entity.Statistic;
import com.zyh.entity.User;
import com.zyh.entity.UserVO;
import com.zyh.service.StatisticService;
import com.zyh.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@CrossOrigin
public class UserController {

    @Autowired
    private UserService tUserService;
    @Autowired
    private StatisticService statisticService;


    @PostMapping("/login")
    @ResponseBody
    public User login(User user) {
        User user1 = tUserService.selectUserBypwd(user);
        if (user1 != null) {
            return user1;
        } else {
            return null;
        }

    }


    //查询所有的用户信息
    @GetMapping("/getAllUser")
    @ResponseBody
    public Map<String, Object> getAllUser(UserVO userVO) {
        if (userVO.getPage() == 0) {
            userVO.setPage(1);
        }
        Integer start = (userVO.getPage() - 1) * userVO.getLimit();
        userVO.setStart(start);
        Map<String, Object> map = new HashMap<>();
        List<User> tUser = tUserService.getAllUser(userVO);
        map.put("code", 0);
        map.put("msg", "请求成功");
        map.put("count", tUserService.getUserCount(userVO));
        map.put("data", tUser);
        return map;
    }

    @GetMapping("/selectUser{id}")
    @ResponseBody
    public Map<String, Object> selectUser(@PathVariable("id") Integer id) {
        User user = tUserService.selectUser(id);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "请求成功");
        map.put("count", 1);
        map.put("data", user);
        return map;
    }

    //    //修改
    @PostMapping("/updateArticleWithId")
    @ResponseBody
    public Map<String, Object> updateArticleWithId(User user) {
        Map<String, Object> map = new HashMap<>();
        Integer integer = tUserService.updateUserWithId(user);
        map.put("code", 0);
        map.put("msg", "修改成功");
        map.put("count", 1);
        map.put("data", integer);
        return map;
    }


    //添加
    @PostMapping("/addUser")
    @ResponseBody
    public Map<String, Object> addUser(User user) {
        Map<String, Object> map = new HashMap<>();
        Integer integer = tUserService.addUser(user);
        map.put("code", 0);
        map.put("msg", "添加成功");
        map.put("count", 1);
        map.put("data", integer);
        return map;

    }


    //删除
    @GetMapping("/DeleteUserByids")
    @ResponseBody
    public Map<String, Object> DeleteUserByids(Integer[] ids) {
        Map<String, Object> map = new HashMap<>();
        Integer idd = null;
        idd = tUserService.DeleteUserByids(ids);
//        for (Integer i:ids) {
//             idd = myService.DeleteArticleByids(i);
//        }
        map.put("code", 0);
        map.put("msg", "删除成功");
        map.put("count", 1);
        map.put("data", idd);
        return map;
    }


    //修改开关
    @PostMapping("/updateenable")
    @ResponseBody
    public int updateenable(User user) {
        return tUserService.updateenable(user);
    }


    //修改个人信息
    @PostMapping("/updatemyself/{id}")
    @ResponseBody
    public Map<String, Object> updatemyself(@PathVariable("id") Integer id, User user) {
        Map<String, Object> map = new HashMap<>();
        Integer integer = tUserService.updatemyself(user);
        map.put("code", 0);
        map.put("msg", "修改成功");
        map.put("count", 1);
        map.put("data", integer);
        return map;
    }

    @RequestMapping("uploadImage")
    @ResponseBody
    public Map<String, Object> uploadImage(MultipartFile file, User user) {
        // File path = new File("f:/image");  //本地系统
        File path = new File("/image/");  //远端服务器系统
        if (!path.exists()) {
            path.mkdir();
        }
        File newFile = new File(path, getfileName(file));
        try {
            file.transferTo(newFile);
            user.setUserAvatar(newFile.getName());
            tUserService.updatephotos(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("res", newFile.getName());
        return map;
    }

    public String getfileName(MultipartFile file) {
        UUID uuid = UUID.randomUUID();
        String filename = file.getOriginalFilename();
        String prefix = filename.substring(filename.lastIndexOf(".") + 1);
        return uuid.toString() + "." + prefix;

    }


    @PostMapping("/updatestatic")
    @ResponseBody
    public Map<String, Object> updatestatic(Statistic statistic) {
        Map<String, Object> map = new HashMap<>();
        Integer integer = statisticService.upadtestatistic(statistic);
        map.put("code", 0);
        map.put("msg", "修改成功");
        map.put("count", 1);
        map.put("data", integer);
        return map;
    }


    @ResponseBody
    @RequestMapping("/getPCA")
    public Object getPCA(String flag, String code) {
        if (flag != null) {
            if (flag.equals("p")) {
                return (Object) tUserService.getProvince();
            } else if (flag.equals("c")) {
                return (Object) tUserService.getCity(code);
            } else {
                return (Object) tUserService.getArea(code);
            }
        } else {
            return null;
        }


    }

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    /*******************************验证码逻辑*******************************************************************?/
     /**
     * 生成验证码
     */
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {

        try {

            //设置相应类型,告诉浏览器输出的内容为图片
            response.setContentType("image/jpeg");

            //设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);

            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();

            randomValidateCode.getRandomCode(request, response);//输出验证码图片方法

        } catch (Exception e) {

            logger.error("获取验证码失败>>>>   ", e);

        }

    }

    /**
     * 校验验证码
     */
    @ResponseBody
    @RequestMapping(value = "/checkVerify", method = RequestMethod.POST, headers = "Accept=application/json")
    public boolean checkVerify(@RequestParam String verifyInput, HttpServletRequest request) {
        try {

            //从session中获取随机数
            String inputStr = verifyInput;


            if (!RandomValidateCodeUtil.vcode.equalsIgnoreCase(inputStr)) {
                return false;
            } else {
                return true;
            }

        } catch (Exception e) {
            logger.error("验证码校验失败", e);
            return false;
        }
    }

}
